package com.leecreate.tutool.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.leecreate.tutool.domain.application.*;
import com.leecreate.tutool.service.ApplicationService;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("applicationService")
public class ApplicationServiceImpl implements ApplicationService {

    @Override
    public int createApplication(String applicationToken, int solutionSetId, String baseURL) {
        Unirest.setTimeouts(0, 0);
        RequestInfo RequestInfo = new RequestInfo();
        RequestInfo.setExecutionMode("NewWithContext");
        RequestInfo.setExecuteLatestVersion(true);
        RequestInfo.setSolutionSetId(solutionSetId);

        Fields fields = new Fields();

        Applicants_IO applicantsIo = new Applicants_IO();
        List<Applicant> applicantList = new ArrayList<>();
        Applicant applicant = new Applicant();
        applicant.setConsent("Y");
        applicant.setInfoDeclaration("Y");

        applicant.setPrivacyPolicy("Y");
        applicant.setTermsConditions("Y");
        applicant.setOTPResult("Pass");

        applicantList.add(applicant);
        applicantsIo.setApplicant(applicantList);

        fields.setApplicants_IO(applicantsIo);
        fields.setServiceType("NewApplication");
        fields.setExternalApplicationId("xxxxxxxxxxxx");

        ApplicationBean applicationBean = new ApplicationBean();
        applicationBean.setRequestInfo(RequestInfo);
        applicationBean.setFields(fields);

        String body = JSONUtil.toJsonStr(applicationBean);

        HttpResponse<String> response = null;
        try {
            response = Unirest.post(baseURL + "/applications").header("Content-Type", "application/json").header("Authorization", "Bearer " + applicationToken).body(body).asString();
        } catch (UnirestException e) {
            throw new RuntimeException(e);
        }
        Map applicationMap = JSON.parseObject(response.getBody(), Map.class);
        Map responseInfoMap = (Map) applicationMap.get("ResponseInfo");
        int applicationId = (int) responseInfoMap.get("ApplicationId");
        return applicationId;
    }
}
